"use client";
import { AntdRegistry } from "@ant-design/nextjs-registry";
import "./globals.css";
import BasicLayout from "@/layouts/BasicLayout";
import React, { useCallback, useEffect } from "react";
import {Provider, useDispatch} from "react-redux";
import store, {AppDispatch} from "@/stores";
import { AxiosError } from "axios";
import { getCurrentUserUsingGet } from "@/api/userController";
import {setLoginUser} from "@/stores/loginUser";
import {usePathname} from "next/navigation";

/**
 * 全局初始化逻辑
 * @param children
 * @constructor
 */
const InitLayout: React.FC<
  Readonly<{
    children: React.ReactNode;
  }>
> = ({ children }) => {
  /**
   * 全局初始化函数，全局单次调用的代码 可写这里
   * 初始化全局用户状态
   */
  const dispatch = useDispatch<AppDispatch>();
  const pathname = usePathname();

  const doInitLoginUser = useCallback(async () => {
    // 如果是登录或注册页面，不获取用户信息
   /* if (pathname.startsWith("/user/login") || pathname.startsWith("/user/register")) {
      return;
    }

    try {
      const res = await getCurrentUserUsingGet();
      if (res.data) {
        dispatch(setLoginUser(res.data));
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      // 如果是网络错误，可能是后端服务未启动
      if (error instanceof AxiosError && error.code === 'ERR_NETWORK') {
        console.warn('后端服务可能未启动，请检查服务状态');
      }
    }*/
  }, [dispatch, pathname]);

  //useEffect 接收一个回调函数和一个空的依赖数组 []，表示仅在组件挂载时执行一次
    useEffect(() => {
      doInitLoginUser();
    }, [doInitLoginUser]);

  return children;
};
export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="zh">
      <body>
        <AntdRegistry>
          <Provider store={store}>
          <InitLayout>
              <BasicLayout>{children}</BasicLayout>
          </InitLayout>
          </Provider>
        </AntdRegistry>
      </body>
    </html>
  );
}
